package org.robot.scm.infra;

import com.fasterxml.jackson.core.type.TypeReference;
import java.util.List;
import java.util.Random;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.pojos.proxy.ProxyInfo;
import org.robot.scm.utils.JsonHelper;
import org.robot.scm.utils.StreamUtils;

/**
 * @Author : Awn create on 2023/8/5 15:10
 */
@Slf4j
public class ProxyHelper {

    private static final String PROXY_KEY = "proxy_ip_list";

    @SneakyThrows
    public static ProxyInfo get() {
        try {
            List<ProxyInfo> proxyInfos = JsonHelper.toList(LocalCacheHelper.get(PROXY_KEY), new TypeReference<>() {
            });
            ProxyInfo[] proxyInfo = proxyInfos.toArray(new ProxyInfo[0]);
            ProxyInfo bean = proxyInfo[new Random().nextInt(proxyInfos.size())];
            log.info("using {}:{} as proxy ip", bean.getProxyIp(), bean.getProxyPort());
            return bean;
        } catch (Exception ignored) {
        }
        return null;
    }

    /**
     * 无效IP移除
     */
    public static void remove(String invalidIp) {
        log.info("{} is invalid, remove from proxy pool", invalidIp);
        List<ProxyInfo> proxyInfos = JsonHelper.toList(LocalCacheHelper.get(PROXY_KEY), new TypeReference<List<ProxyInfo>>() {
        });
        proxyInfos = StreamUtils.filter(proxyInfos, e -> !StringUtils.equals(e.getProxyIp(), invalidIp));
        if (CollectionUtils.isEmpty(proxyInfos)) {
            ProxyLoaderHelper.loadProxy();
            return;
        }
        LocalCacheHelper.remove(PROXY_KEY);
        LocalCacheHelper.put(PROXY_KEY, JsonHelper.toJSONString(proxyInfos));
    }
}
